package myapp.camera;

import java.util.ArrayList;
import myapp.DTO.ServiceDTO;
import myapp.EnumAndConstans.Constants;
import myapp.database.ItemDB;
import myapp.googlemap.GoogleMapActivity;
import myapp.googlemap.R;
import myapp.services.DbServiceHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.content.res.Configuration;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;

public class SearchActivity extends Activity {

	static ArrayList<ServiceDTO> service_data_original;
	ArrayList<ServiceDTO> service_data;
	ArrayList<ServiceDTO> services_download;
	ArrayList<ServiceDTO> service_data_loading;
	ItemAdapter itemAdapter;
	private ListView listViewItemSearch;
	int positionItem = -1;
	EditText searchText;
	Context context;
	static EndlessScrollListener scrollListener;
	
	static LoadDataTask loadDataTask;
	
	private LayoutInflater mInflater;
	// footer view
	private View mFooterView;
	// private TextView mLabLoadMore;
	private ProgressBar mProgressBarLoadMore;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_search);
		context = this;
		if (service_data_original == null)
		{
			service_data_original = new ArrayList<ServiceDTO>();
			try
			{
				ItemDB iDB = new ItemDB(context);
				iDB.open();
				service_data_original = iDB.getAllServices();
				iDB.close();
			}
			catch(Exception e)
			{}
		}
		if (service_data == null)
			service_data = new ArrayList<ServiceDTO>();
		service_data_loading = new ArrayList<ServiceDTO>();
		itemAdapter = new ItemAdapter(this, R.layout.listview_item_camera, service_data_loading, null, false);

		
		listViewItemSearch = (ListView) findViewById(R.id.listViewItemSearch);
		
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mFooterView = (RelativeLayout) mInflater.inflate(R.layout.load_more_footer, listViewItemSearch, false);
		mProgressBarLoadMore = (ProgressBar) mFooterView.findViewById(R.id.load_more_progressBar);
		listViewItemSearch.addFooterView(mFooterView);
		listViewItemSearch.invalidate();
		
		listViewItemSearch.setAdapter(itemAdapter);
		listViewItemSearch.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				positionItem = position;
				openOptionsMenu();
			}
		});
		loadDataTask = new LoadDataTask();
		scrollListener = new EndlessScrollListener() {
			
			@Override
			protected void onLoadMoreData(int page) {
				// TODO Auto-generated method stub
				if (loadDataTask.getStatus() != AsyncTask.Status.RUNNING)
				{
					loadDataTask = new LoadDataTask();
					loadDataTask.execute();
				}
			}
			
			@Override
			protected boolean hasMoreDataToLoad() {
				// TODO Auto-generated method stub
				if (service_data.size() > service_data_loading.size())
					return true;
				return false;
			}
		};
		
		listViewItemSearch.setOnScrollListener(scrollListener);
		

		
		LinearLayout linearLayout_searchOnServer = (LinearLayout) findViewById(R.id.linearLayout_search_more);
		linearLayout_searchOnServer.setVisibility(View.GONE);

		searchText = (EditText) findViewById(R.id.editText_search);
		Button searchButton = (Button) findViewById(R.id.button_search);
		searchButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {				
				
				if (!searchText.getText().toString().trim().equals("")) {		        
			        String TuTimKiem = myapp.helper.ConvertVietNamChar.LocDau(searchText.getText().toString().trim());
					service_data.clear();
					for (int i = 0; i < service_data_original.size(); i++) {
						String TenDichVu = myapp.helper.ConvertVietNamChar.LocDau(service_data_original.get(i).getName());
						if (TenDichVu.toLowerCase().contains(TuTimKiem.toLowerCase()))
							service_data.add(service_data_original.get(i));
					}					
					
					updateListView(service_data);
					
					/*
					 * The service cannot found. Do you want to search on server?
					 */
					if (service_data.size() == 0)
					{
						new AlertDialog.Builder(context)
						.setIcon(R.drawable.icon_attention)
						.setTitle("Not Found")
						.setMessage("The service cannot found. Do you want to search on server?")
						.setPositiveButton("Yes", new DialogInterface.OnClickListener() {						
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								if (!searchText.toString().equals("")) {
									try
									{
									final ProgressDialog pd = ProgressDialog.show(context, "Download", "Downloading... please wait", true);
									
									Thread t = new Thread(new Runnable() {
										@Override
										public void run() {
											// your code
											try {
												DbServiceHelper sH = new DbServiceHelper();
												service_data.clear();
												services_download = new ArrayList<ServiceDTO>();
												services_download = sH
														.getServicesByKeyWord(searchText
																.getText().toString());

											} catch (Exception ex) {

											}
											pd.dismiss();
										}
									});

									pd.setOnDismissListener(new OnDismissListener() {
										@Override
										public void onDismiss(DialogInterface dialog) {
											// TODO Auto-generated method stub
											try {
												service_data.clear();
												for (ServiceDTO s : services_download)
													service_data.add(s);
												updateListView(service_data);
											}

											catch (Exception ex) {

											}
										}
									});

									t.start();

									}
									catch (Exception ex)
									{
										Log.i("Search_onserver", ex.toString());
									}
								}
							}
						} )
						.setNegativeButton("No", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								dialog.dismiss();
							}
						})
						.show();
					}
				}

				// finish();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
			}
		});

		Button search_more_Button = (Button) findViewById(R.id.button_search_more);
		search_more_Button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				LinearLayout linearLayout_searchOnServer = (LinearLayout) findViewById(R.id.linearLayout_search_more);

				if (linearLayout_searchOnServer.getVisibility() == View.VISIBLE)
					linearLayout_searchOnServer.setVisibility(View.GONE);
				else
					linearLayout_searchOnServer.setVisibility(View.VISIBLE);
			}
		});

		
		Button search_on_server_Button = (Button) findViewById(R.id.button_search_on_server);
		search_on_server_Button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (!searchText.toString().equals("")) {
					try
					{
					final ProgressDialog pd = ProgressDialog.show(context, "Download", "Downloading... please wait", true);
					
					Thread t = new Thread(new Runnable() {
						@Override
						public void run() {
							// your code
							try {
								DbServiceHelper sH = new DbServiceHelper();
								service_data.clear();
								services_download = new ArrayList<ServiceDTO>();
								services_download = sH
										.getServicesByKeyWord(searchText
												.getText().toString());

							} catch (Exception ex) {

							}
							pd.dismiss();
						}
					});

					pd.setOnDismissListener(new OnDismissListener() {
						@Override
						public void onDismiss(DialogInterface dialog) {
							// TODO Auto-generated method stub
							try {
								service_data.clear();								
								service_data.addAll(services_download);
								updateListView(service_data);
							}

							catch (Exception ex) {

							}
						}
					});

					t.start();

					}
					catch (Exception ex)
					{
						Log.i("Search_onserver", ex.toString());
					}
				}
			}
		});

	}

	private void updateListView(ArrayList<ServiceDTO> services)
	{
		service_data_loading.clear();
		int visibleThreshold = (Constants.VISIBLE_THRESHOLD < services.size())?Constants.VISIBLE_THRESHOLD:services.size();
		for (int i = 0; i < visibleThreshold; i++)
			service_data_loading.add(services.get(i));
		itemAdapter.updateArrayList(service_data_loading);
		itemAdapter.notifyDataSetChanged();
	}

	
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	// TODO Auto-generated method stub
    	super.onConfigurationChanged(newConfig);
    }
    
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0);
		getMenuInflater().inflate(R.menu.search_menu, menu);
		return true;
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		// TODO Auto-generated method stub
		return super.onMenuOpened(featureId, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		if (this.positionItem == -1)
			return super.onOptionsItemSelected(item);
		switch (item.getItemId()) {

		case R.id.map: {
			Intent myIntent = new Intent(SearchActivity.this,
					GoogleMapActivity.class);
			myIntent.putExtra("serviceItem", service_data.get(positionItem));
			myIntent.putExtra("state_of_googlemap", Constants.STATE_GOOGLEMAP_DISPLAY_ONE_SERVICE);
			startActivity(myIntent);
			return true;
		}

		case R.id.detail: {
			Intent myIntent = new Intent(SearchActivity.this,
					DetailActivity.class);
			myIntent.putExtra("serviceItem", service_data.get(positionItem));
			startActivity(myIntent);
			return true;
		}

		case R.id.interact_view: {
			Intent myIntent = new Intent(SearchActivity.this,
					InteractActivity.class);
			myIntent.putExtra("serviceItem", service_data.get(positionItem));
			startActivity(myIntent);
			return true;
		}

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private class LoadDataTask extends AsyncTask<Void, Void, Void> {
		ArrayList<ServiceDTO> temp_services;
		@Override
		protected Void doInBackground(Void... params) {

			if (isCancelled()) {
				return null;
			}
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                	mFooterView.setVisibility(View.VISIBLE);
                	mProgressBarLoadMore.setVisibility(ProgressBar.VISIBLE);
                }
            });

			// Simulates a background task
			try {				
				Thread.sleep(300);
			} catch (InterruptedException e) {
			}
			


			int visibleThreshold = (service_data_loading.size() + Constants.VISIBLE_THRESHOLD < service_data.size())
					?Constants.VISIBLE_THRESHOLD
					:service_data.size()-service_data_loading.size();
			temp_services = new ArrayList<ServiceDTO>();
			temp_services.addAll(service_data_loading);
	        Log.i("doInBackground_service_data.size()", String.valueOf(service_data.size()));
	        Log.i("doInBackground_service_data_loading.size()", String.valueOf(service_data_loading.size()));
	        Log.i("doInBackground_visibleThreshold", String.valueOf(visibleThreshold));
	        
			for (int i = service_data_loading.size(); i < service_data_loading.size()+ visibleThreshold; i++)
				temp_services.add(service_data.get(i));


			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (mFooterView != null)
			mFooterView.setVisibility(View.GONE);
			mProgressBarLoadMore.setVisibility(ProgressBar.GONE);

			service_data_loading.clear();
			service_data_loading.addAll(temp_services);
			itemAdapter.updateArrayList(service_data_loading);
			itemAdapter.notifyDataSetChanged();
			scrollListener.onLoadingComplete();
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			// Notify the loading more operation has finished
			scrollListener.onLoadingComplete();
		}
	}
}
